//
//  QLNiceChatViewController.m
//  Nice
//
//  Created by huangyueqi on 2017/7/27.
//  Copyright © 2017年 sjyt. All rights reserved.
//

#import "QLNiceChatViewController.h"
#import "QLNiceChatLeftCell.h"
#import "QLNiceChatRightCell.h"
#import "QLNiceChatModel.h"
#import "QLNiceHomeViewController.h"
#import <SocketRocket/SRWebSocket.h>

@interface QLNiceChatViewController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, SRWebSocketDelegate>

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewBottomConstraint;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHeightConstraint;
@property (nonatomic, strong) NSMutableArray *dataList;
@property (nonatomic, assign) CGFloat keyboardHeight;
@property (nonatomic, strong) SRWebSocket *webSocket;

@end

@implementation QLNiceChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self reconnect];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    self.webSocket.delegate = nil;
    [self.webSocket close];
    self.webSocket = nil;
}

#pragma mark - SetupUI
- (void)setupUI {
    
    self.textField.delegate = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    QLNiceChatModel *model = self.dataList[indexPath.row];
    if (!model.isMyself) {
        QLNiceChatLeftCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LeftCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.chatModel = self.dataList[indexPath.row];
        return cell;
    } else {
        QLNiceChatRightCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RightCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.chatModel = self.dataList[indexPath.row];
        return cell;
    }
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    QLNiceChatModel *chatModel = self.dataList[indexPath.row];
    return chatModel.cellHeight;
}

#pragma mark - SRWebSocketDelegate
- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
    
    NSLog(@"Websocket Connected");
}

- (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error{
    
    NSLog(@":( Websocket Failed With Error %@", error);
    self.webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message{
    
    NSLog(@"message ==> %@", message);
    
    NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
    QLNiceChatModel *chatModel = [QLNiceChatModel chatModelWithDict:dict];
    chatModel.isMyself = NO;
    [self.dataList addObject:chatModel];
    [self.tableView reloadData];
    [self tableViewScrollToBottom];
}

- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean{
    
    self.webSocket = nil;
}

- (void)webSocket:(SRWebSocket *)webSocket didReceivePong:(NSData *)pongPayload{
    
    NSString *reply = [[NSString alloc] initWithData:pongPayload encoding:NSUTF8StringEncoding];
    NSLog(@"%@",reply);
}

#pragma mark - Action
//获取键盘高度计算偏移量
- (void)keyboardWillShow:(NSNotification *)notification {
    
    //获取键盘的值
    CGRect keyboardRect = [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //最后获取高度 宽度也是同理可以获取
    self.keyboardHeight = keyboardRect.size.height;
    self.bottomViewBottomConstraint.constant = self.keyboardHeight;
    [self tableViewScrollToBottom];
}

- (void)keyboardWillHide:(NSNotification *)notification {
    
    self.keyboardHeight = 0;
    self.bottomViewBottomConstraint.constant = 0;
}

- (IBAction)closeButton:(id)sender {
    
    [self.textField resignFirstResponder];
    QLNiceHomeViewController *vc = [[UIStoryboard storyboardWithName:@"QLNice" bundle:nil] instantiateViewControllerWithIdentifier:@"QLNiceHomeViewController"];
    [self presentViewController:vc animated:YES completion:nil];
}

- (IBAction)sendButton:(id)sender {
    
    QLNiceChatModel *chatModel = [[QLNiceChatModel alloc] init];
    NSDictionary *dict = @{@"umsg":self.textField.text, @"uname":@"juck"};
    NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
    NSString *sendString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (self.webSocket) {
        [self.webSocket send:sendString];
    }
    chatModel.isMyself = YES;
    chatModel.umsg = self.textField.text;
    [self.dataList addObject:chatModel];
    [self.tableView reloadData];
    self.textField.text = nil;
    [self tableViewScrollToBottom];
}

- (void)tableViewScrollToBottom {
    
    CGFloat offset = self.tableView.contentSize.height + self.topViewHeightConstraint.constant - (self.view.bounds.size.height - self.keyboardHeight) + self.bottomViewHeightConstraint.constant;
    if (offset < 0) {
        offset = 0;
    }
    [self.tableView setContentOffset:CGPointMake(0, offset) animated:YES];
}

//初始化
- (void)reconnect{
    
    self.webSocket.delegate = nil;
    [self.webSocket close];
    self.webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://192.168.33.65:8080"]]];
    self.webSocket.delegate = self;
    [self.webSocket open];
}

#pragma mark - 懒加载
- (NSMutableArray *)dataList {
    
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
